package com.example.google_map_test;

import java.io.File;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.json.JSONArray;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MenuItem.OnMenuItemClickListener;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.ItemizedOverlay;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;

public class MainActivity extends MapActivity {
	private MapView mapView;
	private MapController mapController;
	private MyLocationOverlay mylayer;

	double x0;
	double y0;
	double x1;
	double y1;

	// public DBConnection helper;
	public int id_this;

	List<Overlay> mapOverlays;
	Drawable drawable;
	HelloItemizedOverlay itemizedOverlay;

	public interface UserSchema {
		String TABLE_NAME = "Users"; // Table Name
		String ID = "_id"; // ID
		String USER_NAME = "user_name"; // User Name
		String ADDRESS = "address"; // Address
		String TELEPHONE = "telephone"; // Phone Number
		String MAIL_ADDRESS = "mail_address"; // Mail Address
		String PHOTO_ADDRESS = "photo_address";
	}

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		// 這是讀取資料庫

		// helper = new DBConnection(this);
		// final SQLiteDatabase db = helper.getWritableDatabase();
		// Cursor cursor = db.query(UserSchema.TABLE_NAME, //資料表名稱
		// new String[] {UserSchema.ID,UserSchema.USER_NAME,
		// UserSchema.TELEPHONE,
		// UserSchema.ADDRESS,UserSchema.MAIL_ADDRESS,UserSchema.PHOTO_ADDRESS},
		// //欄位名稱
		// null, // WHERE
		// null, // WHERE 的參數
		// null, // GROUP BY
		// null, // HAVING
		// null // ORDOR BY
		// ); //取得SQLite類別的回傳值:Cursor物件
		// int rows_num = cursor.getCount(); //取得資料表列數
		//
		// cursor.moveToFirst(); //將指標移至第一筆資料
		// for(int i=0; i<rows_num; i++) {
		// String id = cursor.getString(0); //取得第0欄的資料，根據欄位type使用適當語法
		// String name = cursor.getString(1);
		// String latitude = cursor.getString(2);
		// String longitude = cursor.getString(3);
		//
		// Log.i("id", id);
		// Log.i("name", name);
		// Log.i("latitude", latitude);
		// Log.i("longitude", longitude);
		//
		// cursor.moveToNext(); //將指標移至下一筆資料
		// }
		// //cursor.close();

		// findControl(); 原本是在下面

		mapView = (MapView) findViewById(R.id.mapview);
		mapView.setBuiltInZoomControls(true);
		mapView.setSatellite(false);
		mapController = mapView.getController();
		mapController.setZoom(16);
		// 定位點
		List<Overlay> overlays = mapView.getOverlays();
		mylayer = new MyLocationOverlay(this, mapView);
		// 顯示羅盤
		mylayer.enableCompass();
		// 啟動更新(如果坐標有變動會跟著移動)
		mylayer.enableMyLocation();
		mylayer.runOnFirstFix(new Runnable() {
			public void run() {
				mapController.animateTo(mylayer.getMyLocation());
			}
		});

		overlays.add(mylayer);

		GeoPoint gp = mapView.getProjection().fromPixels(0, 0);// 左上角的座標
		x0 = gp.getLatitudeE6() / 1E6;// 取得經緯度
		y0 = gp.getLongitudeE6() / 1E6;
		gp = mapView.getProjection().fromPixels(mapView.getWidth(),
				mapView.getHeight());// 右下角的座標
		x1 = gp.getLatitudeE6() / 1E6;
		y1 = gp.getLongitudeE6() / 1E6;
		Toast.makeText(this, x0 + "~~" + y0 + "~~" + x1 + "~~" + y1,
				Toast.LENGTH_SHORT).show();
		doMultiPost();

		// mapView.setOnTouchListener(this);

		mapOverlay myOverlay = new mapOverlay();
		List<Overlay> overlays2 = mapView.getOverlays();
		overlays2.add(myOverlay);

		// 宣告地標圖示
		Drawable point_star = getResources().getDrawable(
				android.R.drawable.star_on);
		// 設定圖示大小
		point_star.setBounds(0, 0, point_star.getMinimumWidth(),
				point_star.getMinimumHeight());

		landmark myLandmark = new landmark(point_star, this);
		overlays.add(myLandmark); // 將地標層加入地圖座標層中

		// 貼上標記
		List<Overlay> mapOverlays = mapView.getOverlays();
		Drawable drawable = this.getResources().getDrawable(
				android.R.drawable.star_on);
		HelloItemizedOverlay itemizedOverlay = new HelloItemizedOverlay(
				drawable, this);

		// cursor.moveToFirst(); //將指標移至第一筆資料
		// for(int i=0; i<rows_num; i++) {
		// String id = cursor.getString(0); //取得第0欄的資料，根據欄位type使用適當語法
		// String name = cursor.getString(1);
		// String latitude = cursor.getString(2);
		// String longitude = cursor.getString(3);
		// String text = cursor.getString(4);
		//
		// Log.i("id", id);
		// Log.i("name", name);
		// Log.i("latitude", latitude);
		// Log.i("longitude", longitude);
		// Log.i("text", text);
		//
		// float a = Float.parseFloat(latitude);
		// float b = Float.parseFloat(longitude);
		//
		// GeoPoint point = new GeoPoint((int)(a*1000000),(int)(b*1000000));
		// OverlayItem overlayitem = new OverlayItem(point, name, id);
		//
		// Drawable marker =
		// this.getResources().getDrawable(android.R.drawable.star_on);
		// int w = marker.getIntrinsicWidth();
		// int h = marker.getIntrinsicHeight();
		// marker.setBounds(-w / 2, -h, w / 2, 0);
		//
		// overlayitem.setMarker(marker); // 将overlayItem1的图标重新设置成marker
		//
		// itemizedOverlay.addOverlay(overlayitem);
		// mapOverlays.add(itemizedOverlay);
		// cursor.moveToNext(); //將指標移至下一筆資料
		// }

		// plus_set = (Button) findViewById(R.id.PLUS_SET);
		//
		// plus_set.setOnClickListener(new Button.OnClickListener(){
		// //@Override
		// public void onClick(View arg0) {
		// // TODO Auto-generated method stub
		//
		// Intent ins=new Intent(MainActivity.this,ADD.class);
		// startActivity(ins);
		// MainActivity.this.finish();
		//
		// }
		//
		// });

	}

	private void doMultiPost() {

		HttpClient client = new DefaultHttpClient();
		HttpPost post = new HttpPost(
				"http://140.116.41.55/OpenIs-Dm/index.php/expert/mobile_data");
		try {
			// setup multipart entity
			MultipartEntity entity = new MultipartEntity(
					HttpMultipartMode.BROWSER_COMPATIBLE);

			List<NameValuePair> params = new ArrayList<NameValuePair>();

			params.add(new BasicNameValuePair("x0", String.valueOf(x0)));
			params.add(new BasicNameValuePair("y0", String.valueOf(y0)));
			params.add(new BasicNameValuePair("x1", String.valueOf(x1)));
			params.add(new BasicNameValuePair("y1", String.valueOf(y1)));
			params.add(new BasicNameValuePair("time", "2012-08-23 15:37:00"));

			
			for (int i = 0; i < params.size(); i++) {
				entity.addPart(params.get(i).getName(), new StringBody(params
						.get(i).getValue(), Charset.forName("UTF-8")));
			}
			post.setEntity(entity);

			 //create response handler
			 ResponseHandler<String> handler = new BasicResponseHandler();
			 //execute and get response
			
		//	HttpResponse response = client.execute(post);
			String response = new String(client.execute(post, handler)
					.getBytes(), HTTP.UTF_8);
			Toast.makeText(this, response, Toast.LENGTH_SHORT).show();
			
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public class mapOverlay extends com.google.android.maps.Overlay {
		public boolean onTouchEvent(MotionEvent event, MapView mapview) {

			if (event.getEventTime() - event.getDownTime() > 2000) {

				GeoPoint p = mapView.getProjection().fromPixels(
						(int) event.getX(), (int) event.getY());

				Toast.makeText(
						getBaseContext(),
						p.getLatitudeE6() / 1E6 + "," + p.getLongitudeE6()
								/ 1E6, Toast.LENGTH_SHORT).show();

				dialog();
			}
			return false;
		}

	}

	protected void dialog() {
		AlertDialog.Builder builder = new Builder(MainActivity.this);
		builder.setMessage("在此地加入一筆資料?");
		builder.setTitle("訊息");
		builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {

			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
				Intent ins = new Intent(MainActivity.this, ADD.class);
				startActivity(ins);
				MainActivity.this.finish();
			}

		});

		builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {

			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
			}
		});

		builder.create().show();
	}

	class landmark extends ItemizedOverlay<OverlayItem> {
		private List<OverlayItem> items = new ArrayList<OverlayItem>();
		private Context context; // 主程式

		public landmark(Drawable defaultMarker) {
			super(defaultMarker);
		}

		public landmark(Drawable defaultMarker, Context context) {
			super(defaultMarker);
			this.context = context;

			GeoPoint station_taipei = new GeoPoint((int) (25.047192 * 1000000),
					(int) (121.516981 * 1000000)); // 設定地圖座標值:緯度,經度
			GeoPoint station_tainan = new GeoPoint(
					(int) (22.99724179778664 * 1000000),
					(int) (120.2126014372952 * 1000000)); // 設定地圖座標值:緯度,經度

			// 加入地標座標值(Point)、標題(Title)、說明(Snippet)
			items.add(new OverlayItem(station_taipei, "台北車站", "台北火車站與高鐵、捷運三鐵共構"));
			items.add(new OverlayItem(station_tainan, "台南車站", "台南火車站"));

			populate(); // 自動完成所有處理程序，呼叫createItem取得所有地標
		}

		@Override
		protected OverlayItem createItem(int i) {
			// TODO Auto-generated method stub
			return items.get(i); // 取得第i個地標
		}

		@Override
		public int size() {
			// TODO Auto-generated method stub
			return items.size(); // 地標總數量，會被populate()呼叫
		}

		@Override
		protected boolean onTap(int index) { // 點擊地標時的反應

			// Intent ins=new Intent(MainActivity.this ,TEST.class);
			// startActivity(ins);

			// TODO Auto-generated method stub
			// 彈出視窗
			AlertDialog.Builder builder = new AlertDialog.Builder(context); // 顯示於主程式main
			builder.setTitle(items.get(index).getTitle()); // 加入標題
			builder.setMessage(items.get(index).getSnippet()); // 加入說明
			builder.setPositiveButton("OK",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
						}
					});
			builder.show();
			return super.onTap(index);
		}
	}

	public static Drawable boundCenter(Drawable d) { // 使圖示中心點對齊地標
		d.setBounds(-d.getIntrinsicWidth() / 2, -d.getIntrinsicHeight() / 2,
				d.getIntrinsicWidth() / 2, d.getIntrinsicHeight() / 2);
		return d;
	}

	// @Override
	// public boolean onCreateOptionsMenu(Menu menu) {
	// getMenuInflater().inflate(R.menu.activity_main, menu);
	// return true;
	// }

	@Override
	protected boolean isRouteDisplayed() {
		// TODO Auto-generated method stub
		return false;
	}

	public class HelloItemizedOverlay extends ItemizedOverlay {
		private ArrayList<OverlayItem> mOverlays = new ArrayList<OverlayItem>();
		private Context mContext = null;

		public HelloItemizedOverlay(Drawable defaultMarker) {
			super(boundCenterBottom(defaultMarker));
			// TODO Auto-generated constructor stub
		}

		public HelloItemizedOverlay(Drawable defaultMarker, Context context) {
			super(boundCenter(defaultMarker));
			mContext = context;
		}

		public void addOverlay(OverlayItem overlay) {
			mOverlays.add(overlay);
			populate();
		}

		@Override
		protected OverlayItem createItem(int i) {
			return mOverlays.get(i);
		}

		@Override
		public int size() {
			return mOverlays.size();
		}

		@Override
		protected boolean onTap(int index) {

			final OverlayItem item = mOverlays.get(index);
			AlertDialog.Builder dialog = new AlertDialog.Builder(mContext);
			dialog.setTitle(item.getTitle());
			// dialog.setMessage(item.getSnippet());
			dialog.setPositiveButton("OK",
					new DialogInterface.OnClickListener() {

						public void onClick(DialogInterface dialog, int which) {
							Intent ins = new Intent(MainActivity.this,
									ADD_2.class);
							Bundle bundle = new Bundle();
							bundle.putString("name", item.getTitle());
							bundle.putString("id", item.getSnippet());
							ins.putExtras(bundle); // 將參數放入intent

							startActivityForResult(ins, 0);
							startActivity(ins);

						}
					});
			dialog.setNegativeButton("Cancel",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int id) {
						}
					});
			dialog.show();
			return true;
		}

	}

	// public boolean onCreateOptionsMenu(Menu menu)
	// {
	// //获得一个MenuItem对象, 创建一个选项
	// MenuItem deleteMenuItem = menu.add(0, 0, 0, "删除");
	// //为deleteMenuItem选项设置图标
	// deleteMenuItem.setIcon(R.drawable.menu_map);
	// //设置"删除"菜单的单击事件;菜单项单击事件类必须要实现OnMenuItemClickListener接口。
	// deleteMenuItem.setOnMenuItemClickListener((OnMenuItemClickListener)
	// this);
	//
	// //添加"文件"菜单
	// MenuItem fileMenuItem = menu.add(0, 1, 1, "文件");
	// fileMenuItem.setIcon(R.drawable.menu_add);
	// fileMenuItem.setOnMenuItemClickListener((OnMenuItemClickListener) this);
	// return super.onCreateOptionsMenu(menu);
	//
	// }
	//
	// //菜单项单击事件的方法
	//
	// public boolean onMenuItemClick(MenuItem item)
	// {
	// switch(item.getItemId())
	// {
	// case 0:
	// //在这里编写单击响应事件代码，
	// //根据item参数的getItemId()来确定单击的是哪一项菜单。
	// Toast.makeText(this, "文件已删除！", Toast.LENGTH_LONG).show();
	// break;
	//
	// case 1:
	// Toast.makeText(this, "文件", Toast.LENGTH_LONG).show();
	// break;
	// }
	// return false;
	// }

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {

		menu.add(0, 1, 1, "地圖").setIcon(R.drawable.menu_map);
		menu.add(0, 2, 2, "增加").setIcon(R.drawable.menu_add);
		menu.add(0, 3, 3, "檢視").setIcon(R.drawable.menu_view);
		menu.add(0, 4, 4, "訊息").setIcon(R.drawable.menu_help);
		return true;

	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case 1:
			break;
		case 2:

			Intent ins = new Intent(MainActivity.this, Map_ADD.class);
			startActivity(ins);
			MainActivity.this.finish();
			break;
		case 3:
			Toast.makeText(this, "帮助菜单被点击了", Toast.LENGTH_LONG).show();
			break;
		case 4:
			Toast.makeText(this, "添加菜单被点击了", Toast.LENGTH_LONG).show();
			break;

		}

		return false;
	}

	// public static class DBConnection extends SQLiteOpenHelper {
	// private static final String DATABASE_NAME = "PhoneBookDB";
	// private static final int DATABASE_VERSION = 1;
	// private DBConnection(Context ctx) {
	// super(ctx, DATABASE_NAME, null, DATABASE_VERSION);
	// }
	// public void onCreate(SQLiteDatabase db) {
	// String sql = "CREATE TABLE " + UserSchema.TABLE_NAME + " ("
	// + UserSchema.ID + " INTEGER primary key autoincrement, "
	// + UserSchema.USER_NAME + " text not null, "
	// + UserSchema.TELEPHONE + " text not null, "
	// + UserSchema.ADDRESS + " text not null, "
	// + UserSchema.MAIL_ADDRESS + " text not null, "
	// + UserSchema.PHOTO_ADDRESS + " text not null "+ ");";
	// //Log.i("haiyang:createDB=", sql);
	// db.execSQL(sql);
	// }
	// public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
	// {
	// // TODO Auto-generated method stub
	// }
	// }

}
